public class Solution1020 {
    int[][] grid;
    boolean[][] isBeen;
    int[][] directArr = new int[][]{new int[]{0, 1}, new int[]{1, 0}, new int[]{0, -1}, new int[]{-1, 0}};
    int beenCount = 0;
    int m;
    int n;

    private boolean isOutOfGrid(int i, int j){
        return i < 0 || i >= m || j < 0 || j >= n;
    }

    private int getLandCount(int[][] grid){
        int landCount = 0;
        for (int[] row : grid) {
            for (int num : row) {
                if(num == 1){
                    landCount++;
                }
            }
        }
        return landCount;
    }

    private void travel(int tmpI, int tmpJ){
        if(isOutOfGrid(tmpI, tmpJ) || isBeen[tmpI][tmpJ] || grid[tmpI][tmpJ] == 0){
            return;
        }
        isBeen[tmpI][tmpJ] = true;
        beenCount++;
        for(int[] direct : directArr){
            travel(tmpI + direct[0], tmpJ + direct[1]);
        }
    }

    private void travelGridFromEdge(){
        for(int i = 0; i < n; i++){
            travel(0, i);
            travel(m - 1, i);
        }
        for(int i = 1; i < m - 1; i++){
            travel(i, 0);
            travel(i, n - 1);
        }
    }

    public int numEnclaves(int[][] grid) {
        this.grid = grid;
        this.m = grid.length;
        this.n = grid[0].length;
        this.isBeen = new boolean[m][n];
        int landCount = getLandCount(grid);
        travelGridFromEdge();
        return landCount - beenCount;
    }

    public static void main(String[] args) {
        Solution1020 s = new Solution1020();
        s.numEnclaves(new int[][]{new int[]{0, 0, 0, 0}, new int[]{1, 0, 1, 0}, new int[]{0, 1, 1, 0}, new int[]{0, 0, 0, 0}});
    }
}
